﻿using Aker.Cikislar;
using Aker.DevTeam;
using Cikislar;
using DevExpress.XtraBars;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;

namespace Aker.Hammadde
{
    public partial class HammaddeCikis : XForm
    {
        DataTable dt;
        string[] editAbleColumns;
        private string filters;
        private int cikisId = -1;

        public HammaddeCikis()
        {
            InitializeComponent();
        }

        public HammaddeCikis(int cikisId, string filters)
        {
            InitializeComponent();
            this.filters = filters;
            this.cikisId = cikisId;
            btnSepeteEkle.Visibility = BarItemVisibility.Never;
            btnSepeteGit.Visibility = BarItemVisibility.Never;
            btnYenile.Visibility = BarItemVisibility.Never;
        }

        private void HammaddeCikis_Load(object sender, EventArgs e)
        {
            editAbleColumns = new string[] { "CikilacakKG", "CikilacakAdet" };
            BindData();
            gv.RowCellStyle += gv_RowCellStyle;
        }



        private void BindData(bool saveOrder = false)
        {
            Dictionary<string, int> cols = new Dictionary<string, int>();
            if (saveOrder)
            {
                for (int i = 0; i < gv.VisibleColumns.Count; i++)
                {
                    GridColumn col = gv.VisibleColumns[i];
                    cols.Add(col.FieldName, col.VisibleIndex);
                }
            }

            if (cikisId == -1)
                dt = Data.DM.ExecuteDataSet("GetHammaddeStok", 2, DBNull.Value).Tables[0];
            else
                dt = Data.DM.ExecuteDataSet("GetHammaddeStok", 2, filters).Tables[0];

            dt.Columns.Add("CikilacakKG", typeof(decimal));
            dt.Columns.Add("CikilacakAdet", typeof(int));

            gv.SetGridId(1);
            gv.Init(dt);


            gv.MakeReadOnly(editAbleColumns);

            gv.SetCaptions("ElyafId:Elyaf No", "IplikId:İplik No", "Aciklama:Açıklama", "FiiliStok:Fiili KG", "FiiliCuvalBot:Adet", "Tedarikci:Tedarikçi", "CikilacakKG:Çıkılacak KG", "CikisKG:Çıkılan KG", "Girilen:Girilen KG", "CikilacakAdet:Çıkılacak Adet", "CikisCuvalBot:Çıkılan Adet", "GirisCuvalBot:Giriş Adet");
            gv.MakeColumnInvisible("IplikId", "ElyafId");
            gv.FormatAsNumber("KG", "CikilacakKG");
            gv.BestFitColumns();
            gv.EnableComplexFiltering("Hammadde");

            gv.Columns["CikilacakKG"].Width = gv.Columns["CikilacakAdet"].Width;
            if (saveOrder)
            {
                foreach (GridColumn gc in gv.Columns)
                {
                    if (cols.ContainsKey(gc.FieldName))
                    {
                        //gc.VisibleIndex = true;
                        gc.VisibleIndex = cols[gc.FieldName];
                    }
                    else
                        gc.Visible = false;
                }
                foreach (KeyValuePair<string, int> pairs in cols)
                {

                }
            }
        }

        void gv_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1 && editAbleColumns.Contains(e.Column.FieldName))
                e.Appearance.BackColor = Color.LightYellow;
        }

        //private void Cikis(object sender, EventArgs e)
        //{
        //    gv.EndEditing();

        //    DataTable changes = dt.GetChanges().DefaultView.ToTable("Table", false, "HammaddeId", "CikisKG");
        //    string xml = changes.Serialize();
        //    Data.DM.ExecuteNonQuery("InsCikis", 1, xml, AppSession.UserInfo.UserId);
        //    { }
        //}


        private bool Kontrol()
        {
            gv.EndEditing();

            DataTable changes = dt.GetChanges();
            if (changes != null && changes.Rows.Count > 0)
            {
                foreach (DataRow dr in changes.Rows)
                {
                    //TODO ACİL
                    //decimal gKG = dr["GirilenKG"].ToDecimalNN();
                    //int gCuvalBot = dr["GirilenAdet"].ToIntNN();
                    //decimal KG = dr["CikilacakKG"].ToDecimalNN();
                    //int CuvalBot = dr["CikilacakAdet"].ToIntNN();

                    //if (KG > 0 && gCuvalBot > 0 && CuvalBot < 1)
                    //{
                    //    ShowError("Giriş çuval/bot varken çıkışta çuval/bot yazmak mecburidir !");
                    //    return false;
                    //}
                }

                return true;
            }
            else
            {
                ShowInfo("Değişiklik yok.");
                return false;
            }
        }


        private void btnTemizle_ItemClick(object sender, ItemClickEventArgs e)
        {
            gv.EndEditing();
            foreach (DataRow dr in dt.Select("isnull(CikilacakKG,0) > 0 or isnull(CikilacakAdet,0) > 0"))
            {
                dr["CikilacakKG"] = DBNull.Value;
                dr["CikilacakAdet"] = DBNull.Value;
            }
            dt.AcceptChanges();
        }

        private void btnSepeteEkle_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (Kontrol())
            {
                DataTable changes = dt.GetChanges();
                foreach (DataRow dr in changes.Rows)
                {
                    AkerDB.CikisLinesRow cikisLines = CikisSepet.YeniCikisLines();

                    cikisLines.IplikId = dr["IplikId"].ToIntNN();
                    cikisLines.ElyafId = dr["ElyafId"].ToIntNN();
                    cikisLines.CikilanKG = dr["CikilacakKG"].ToDecimalNN();
                    cikisLines.CikilanAdet = dr["CikilacakAdet"].ToIntNN();
                    cikisLines["Hammadde"] = dr["Hammadde"];

                    CikisSepet.SepeteAt(cikisLines);
                }
                btnTemizle.PerformClick();
                ShowInfo("Sepete atıldı.");
            }
        }


        private void btnCik_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (Kontrol())
            {
                if (cikisId == -1)
                {
                    Cikis.TamponuTemizle();
                    DataTable changes = dt.GetChanges();
                    foreach (DataRow dr in changes.Rows)
                    {
                        AkerDB.CikisLinesRow cikisLines = Cikis.YeniTamponSatiri();

                        cikisLines.IplikId = dr["IplikId"].ToIntNN();
                        cikisLines.ElyafId = dr["ElyafId"].ToIntNN();
                        cikisLines.CikilanKG = dr["CikilacakKG"].ToDecimalNN();
                        cikisLines.CikilanAdet = dr["CikilacakAdet"].ToIntNN();

                        Cikis.TamponaEkle(cikisLines);
                    }

                    if (Cikis.TamponuCik(2) == System.Windows.Forms.DialogResult.OK)
                    {
                        BindData(true);
                        ShowInfo("Çıkış başarıyla gerçekleştirildi.");
                    }
                }
                else
                {
                    DataTable changes = dt.GetChanges();
                    foreach (DataRow dr in changes.Rows)
                    {
                        AkerDB.CikisLinesDataTable cl = new AkerDB.CikisLinesDataTable();
                        AkerDB.CikisLinesRow cikisLines = cl.NewCikisLinesRow();

                        cikisLines.CikisId = cikisId;
                        cikisLines.IplikId = dr["IplikId"].ToIntNN();
                        cikisLines.ElyafId = dr["ElyafId"].ToIntNN();
                        cikisLines.CikilanKG = dr["CikilacakKG"].ToDecimalNN();
                        cikisLines.CikilanAdet = dr["CikilacakAdet"].ToIntNN();
                        cikisLines.FixNulls();

                        cl.Rows.Add(cikisLines);
                        Data.TAM.CikisLinesTableAdapter.Update(cl);
                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    }
                }
            }
        }

        private void btnSepeteGit_ItemClick(object sender, ItemClickEventArgs e)
        {
            AppSession.MainForm.ShowMdiChildForm(typeof(Cikislar.CikisSepet));
        }

        private void btnYenile_ItemClick(object sender, ItemClickEventArgs e)
        {
            int HammaddeId = gv.GetFocusedRowCellValue("HammaddeId").ToIntNN();
            BindData(true);
            int rh = gv.LocateByValue("HammaddeId", HammaddeId);
            gv.FocusedRowHandle = rh;
        }
    }
}
